// ignore_for_file: avoid_print

import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 逆地理编码地址结果
  String address = '';
  // 周边的小区
  List nearbyCommunity = [];
  String apiKey = 'ec6f580a9ed57f6731978c15a3a50fb1';
  String baseUrl = 'https://restapi.amap.com/v3';

  @override
  initState() {
    super.initState();
    requestLocationPermission();
    // reverseGeocoding(34.57787, 113.845473);
    // queryNearbyCommunities(34.57787, 113.845473);
  }

  /// 判断是否进行位置授权
  Future<void> requestLocationPermission() async {
    try {
      PermissionStatus status = await Permission.location.request();
      if (status.isGranted) {
        // 权限未授予
        ToastUtil.showSuccess('位置权限授予');
        getCurrentLocation();
      } else {
        // 权限未授予
        ToastUtil.showError('位置权限未授予, 请去设置中心开启');
      }
    } catch (e) {
      print(e);
    }
  }

  /// 异步获取当前设备的位置信息。
  ///
  /// 此方法首先根据设备的平台（Android、iOS/macOS 或 Web）配置不同的定位设置，
  /// 然后使用这些设置获取设备的当前位置，并处理位置信息或异常。
  Future<void> getCurrentLocation() async {
    if (kIsWeb) {
      reverseGeocoding(34.57787, 113.845473);
      queryNearbyCommunities(34.57787, 113.845473);
    } else {
      reverseGeocoding(34.57787, 113.845473);
      queryNearbyCommunities(34.57787, 113.845473);
      // try {
      //   // 使用配置好的定位设置获取当前位置
      //   Position position = await Geolocator.getCurrentPosition();
      //   // 显示成功获取到的纬度和经度
      //   ToastUtil.showSuccess('${position.latitude}, ${position.longitude}');
      //   reverseGeocoding(position.latitude, position.longitude);
      //   queryNearbyCommunities(34.57787, 113.845473);
      //   queryNearbyCommunities(34.57787, 113.845473);
      // } catch (e) {
      //   ToastUtil.showError(e.toString());
      //   // 处理可能出现的异常
      //   print(e.toString());
      // }
    }
  }

  /// 逆地理编码
  Future<void> reverseGeocoding(double latitude, double longitude) async {
    try {
      final response = await http.get(
        // 逆地理编码 API 服务地址
        '$baseUrl/geocode/regeo',
        // 请求参数
        params: {
          // 高德地图官网开发者控制台申请的密钥
          'key': apiKey,
          // 经度在前，纬度在后，经纬度间以“,”分割
          'location': '$longitude,$latitude',
          // 搜索半径
          'radius': 500,
          // 搜索类型
          'type': '住宅小区'
        },
      );
      // 更新地址信息
      setState(() {
        address = response['regeocode']['formatted_address'];
      });
      print(response);
    } catch (e) {
      print('_reverseGeocoding 逆地理编码 error');
      print(e);
    }
  }

  /// 获取附近小区
  Future<void> queryNearbyCommunities(double latitude, double longitude) async {
    try {
      var res = await http.get(
          '$baseUrl/place/around?key=$apiKey&location=$longitude,$latitude&radius=1000&types=住宅小区');

      setState(() {
        nearbyCommunity = res['pois'];
      });
    } catch (e) {
      print(e);
      ToastUtil.showError('获取附近小区出现问题');
    }
  }

  /// 构建小区列表
  List<Widget> _buildCommunityItem(List community) {
    List<Widget> temp = [];
    for (var item in community) {
      temp.add(GestureDetector(
          onTap: () {
            Navigator.pushNamed(context, '/building_list', arguments: {
              // 小区的名称
              'point': item['name']
            });
          },
          child: Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(children: [
                Expanded(child: Text('${item['name']}')),
                const Row(children: [
                  Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black),
                ])
              ]))));
    }
    return temp;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(address)),
                GestureDetector(
                    onTap: () {
                      reverseGeocoding(34.57787, 113.845473);
                    },
                    child: const Row(
                      children: [
                        Icon(Icons.location_searching_outlined,
                            color: Colors.blue),
                        SizedBox(width: 2),
                        Text(
                          '重新定位',
                          style: TextStyle(color: Colors.blue),
                        ),
                      ],
                    ))
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              children: _buildCommunityItem(nearbyCommunity))
        ],
      ),
    );
  }
}
